//postman对参数加密-示例

/*	Body	*/
{
    "body":"{{rsaBody}}"
}


/*	Pre-request Script	*/
var clearText = '{"securityCode":"300059","market":0,"pageNum":10}';
// var clearText = '{"securityCode":"601700","market":1,"pageNum":1}';
// var clearText = '{"securityCode":"601702","market":1,"pageNum":1}';
// var clearText = '{"securityCode":"601717","market":1,"pageNum":1}';
//---------------------------------------------------------------------//
const entry_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXVk3Pyz/zDe/x1z8rLLAk7EPn6PHIiB2toyb33nvxkYhYZDox4Rh4Fq15rTAdhhMyIGcJnielq2QuW+izWtZ+NAazJY3SATBR5Rmh8ZhewCfiysKIN0DbhR9by22sJ9AHs1NHbvWRwBngKkJsX4ADMt2qTY92UGf6tfRMciM0mQIDAQAB';
const forge_url = 'https://gitee.com/lzqklrs/various/raw/master/forge_min.js';
//---------------------------------------------------------------------//
console.info('cleartext: ' + clearText);
if(!pm.globals.has('forgeJS')){
    console.log('request forge.js from ' + forge_url);
    pm.sendRequest(forge_url, function (err, res) {
            if (err) {
                console.error(err);
            } else {
                console.info("request forgs.js: Succeed, please try again");
                pm.globals.set('forgeJS', res.text());
            }
        }
    );
}
eval(pm.globals.get('forgeJS'));
// console.log(pm.globals.get("forgeJS"));

//注意此处上下的BEGIN PRIVATE KEY不要删除，框架自带的
const public_key = '-----BEGIN PUBLIC KEY-----\n'
    + entry_key               
    + '\n-----END PUBLIC KEY-----';
var publicKey = forge.pki.publicKeyFromPem(public_key);
var buffer = forge.util.createBuffer(clearText, 'utf8');
var bytes = buffer.getBytes();
var encryptedText = forge.util.encode64( publicKey.encrypt(bytes, 'RSAES-PKCS1-V1_5', {
        md: forge.md.sha256.create(),
        mgf1: {
            md: forge.md.sha1.create()
        }
    })
);

console.info('encryptedText: '+ encryptedText);
postman.setEnvironmentVariable("rsaBody", encryptedText); 